import traceback

from seleniumwire import webdriver
from selenium.webdriver.chrome.options import Options

from public.Getip import getProxy
from public.config import log, drivers


def launchBrowser(mobile, tid):
        try:
                proxy_ip = getProxy(mobile, tid)
                seleniumwire_options = { 'proxy':{
                        'http': f'http://{proxy_ip}',
                        'https': f'https://{proxy_ip}',
                        'no_proxy': 'localhost,127.0.0.1'
                },
                        'driver_path': '/data/python/jojo/chromedriver-linux64/chromedriver'
                }
                log.info("开始启动浏览器", tid)
                chrome_options = Options()
                chrome_options.add_experimental_option('detach', True)
                chrome_options.add_argument('--headless')  # 启用无头模式
                chrome_options.add_argument('--disable-gpu')  # 禁用GPU加速
                chrome_options.add_argument('--disable-extensions')  # 禁用不必要的插件和扩展
                chrome_options.add_experimental_option('useAutomationExtension', False)  # 不要使用自动化扩展
                chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])  # 防止Chrome在自动化时显示一些通知
                chrome_options.add_argument('--no-sandbox')  # 在Linux中运行时需要添加的选项
                # chrome_options.add_argument(f'--proxy-server={proxy_ip}')
                user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ApleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
                chrome_options.add_argument(f"user-agent={user_agent}")
                # 创建新的 WebDriver 对象并恢复会话d
                driver = webdriver.Chrome(options=chrome_options, seleniumwire_options=seleniumwire_options)
                log.info("浏览器启动成功！正在加载小红书...", tid)
                driver.get("https://creator.xiaohongshu.com/")
                log.info("小红书页面加载完成", tid)
                drivers[mobile] = driver
                return driver
        except:
                msg = traceback.format_exc()
                log.error(f"浏览器启动失败: {msg}", tid)
                return None
